package zzuli.edu.cn.aliyunsms.controller;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import zzuli.edu.cn.aliyunsms.service.SendSMS;

import java.util.HashMap;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@RestController
@CrossOrigin //跨域支持
public class SendSMSController {
    @Autowired
    private SendSMS sendSMS;
    @Autowired
    public RedisTemplate<String,String> redisTemplate;

    @RequestMapping("/sendSMS/{phoneNumber}")
    public String  sendSMS(@PathVariable String phoneNumber) {
        String code = redisTemplate.opsForValue().get(phoneNumber);
        if(!StringUtils.isEmpty(code)){
            return "验证码已存在，尚未过期，您可以继续使用！";
        }

        //生成验证码并保存在redis中
        code = UUID.randomUUID().toString().substring(0, 6);
        HashMap<String, Object> map = new HashMap<>();
        map.put("code",code);
        boolean isSuccess = sendSMS.sendSMS(phoneNumber, "SMS_204111890", map);
        if(isSuccess){
            redisTemplate.opsForValue().set(phoneNumber,code,5, TimeUnit.MINUTES);
            return "发送成功！";
        }else{
            return "发送失败！";
        }
    }
}
